<template>
    <div class="cart">
      <DetailHead></DetailHead>
      <div class="cart-container">
        <div class="cart-header">
          <div class="col-check">
            <input type="checkbox" :checked="allSelected" @change="handleAllCheck">
            <span>全选</span>
          </div>
          <div class="col-name">课程名称</div>
          <div class="col-original">原价</div>
          <div class="col-discount">优惠</div>
          <div class="col-operation">操作</div>
        </div>
  
        <div class="cart-list">
          <div 
            v-for="(item, index) in cartCourses" 
            :key="item.courseId" 
            class="cart-item"
          >
            <div class="col-check">
              <input type="checkbox" :checked="item.selected" @change="handleItemCheck(item.courseId)">
            </div>
  
            <div class="col-name">
              <img :src="item.bannerFileUrlPc" :alt="item.courseTitle" class="course-img">
              <div>
                <div class="main-title">{{ item.courseTitle }}</div>
                <div class="sub-title">{{ item.subtitle }}</div>
              </div>
            </div>

            <div class="col-original">
            <span class="discount-price" style="color: #ff4f23;">￥{{ item.discountPrice }}</span>
              <span :class="{ 'line-through': item.isDiscount }">￥{{ item.coursePrice }}</span>
            </div>
  
            <div class="col-discount">
              <template v-if="item.isDiscount">
                <span class="tag">限时钜惠</span>
              </template>
              <template v-else>¥0</template>
            </div>

            <div class="col-operation">
              <button class="delete-btn" @click="deleteItem(index)">删除</button>
            </div>
          </div>
        </div>
  
        <div class="cart-footer">
          <div class="select-all">
            <input type="checkbox" :checked="allSelected" @change="handleAllCheck">
            <span>全选</span>
          </div>
          <div class="total">
            <span style="margin-right: 10px;">合计:</span><span class="total-price">¥{{ totalPrice !== undefined ? totalPrice.toFixed(2) : '0.00' }}</span>
          </div>
          <button 
              class="submit" 
              :style="{ backgroundColor: allSelected ? '#ff8000' : '#999' }"
          >提交</button>
        </div>
      </div>
      <FootView></FootView>
    </div>
  </template>
  
  <script>
  import DetailHead from '@/components/DetailHead.vue'
  import FootView from '@/components/FootView.vue'
  import { mapState, mapMutations } from 'vuex'
  import { getCourseDetail } from '@/api/request' 
  
  export default {
    name: 'CartView',
    components: { DetailHead, FootView },
    data() {
      return {
        allSelected: false,
        cartCourses: []
      }
    },
    computed: {
      ...mapState(['cartIds']),
      totalPrice() {
        if (!this.cartCourses || this.cartCourses.length === 0) {
          return 0;
        }
        return this.cartCourses.reduce((sum, course) => {
          const discountPriceStr = String(course.discountPrice || '0');
          const coursePriceStr = String(course.coursePrice || '0');
          
          const discountPrice = course.isDiscount 
            ? parseFloat(discountPriceStr.replace('¥', '')) || 0 
            : 0;
          const originalPrice = parseFloat(coursePriceStr.replace('¥', '')) || 0;
          
          if (course.selected && course.isDiscount) {
            return sum + discountPrice;
          } else if (course.selected) {
            return sum + originalPrice;
          }
          return sum;
        }, 0);
      }
    },
    watch: {
      cartIds: {
        immediate: true,
        handler(newIds) {
          this.fetchCartCourses(newIds)
        }
      },
      cartCourses: {
        deep: true,
        handler() {
          this.syncAllSelected()
        }
      }
    },
    methods: {
      ...mapMutations(['UPDATE_CART_IDS']),
      async fetchCartCourses(ids) {
        if (!ids || ids.length === 0) {
          this.cartCourses = [];
          this.syncAllSelected();
          return;
        }

        try {
          const responses = await Promise.all(ids.map(id => getCourseDetail(id)));
          const courses = responses
            .filter(res => res.code === 0)
            .map(res => ({
              ...res.data,
              selected: false
            }));
          this.cartCourses = courses;
          this.syncAllSelected();
        } catch (error) {
          ids.forEach(id => console.error(`获取课程ID:${id}详情失败`, error));
        }
      },
      syncAllSelected() {
        this.allSelected = this.cartCourses.length > 0 && 
                          this.cartCourses.every(course => course.selected)
      },
      handleAllCheck() {
        this.allSelected = !this.allSelected;
        this.cartCourses.forEach(course => {
          course.selected = this.allSelected
        })
      },
      handleItemCheck(courseId) {
        const course = this.cartCourses.find(c => c.courseId === courseId)
        if (course) course.selected = !course.selected
        this.syncAllSelected()
      },
      moveItem(index, direction) {
        const newCourses = [...this.cartCourses]
        if (direction === 'up' && index > 0) {
          [newCourses[index], newCourses[index - 1]] = [newCourses[index - 1], newCourses[index]]
        } else if (direction === 'down' && index < newCourses.length - 1) {
          [newCourses[index], newCourses[index + 1]] = [newCourses[index + 1], newCourses[index]]
        }
        this.cartCourses = newCourses;
        this.UPDATE_CART_IDS(newCourses.map(c => c.courseId))
      },
  
      deleteItem(index) {
        const newCourses = [...this.cartCourses];
        newCourses.splice(index, 1);
        this.cartCourses = newCourses;
        this.UPDATE_CART_IDS(newCourses.map(c => c.courseId));
        this.syncAllSelected();
      },
     
      addToCart(courseId) {
        if (this.cartIds.includes(courseId)) {
          alert('课程已在购物车中');
        } else {
          this.UPDATE_CART_IDS([...this.cartIds, courseId]);
          alert('成功加入购物车');
        }
      }
    }
  }
  </script>
  
  <style scoped lang="scss">

.col-name {
  display: flex;
  align-items: center;
  gap: 10px;

  .course-img {
    width: 156px;
    height: 104px;
    object-fit: cover;
    border-radius: 4px;
  }
}
  .cart-container {
    width: 1160px;
    margin: 20px auto;
    padding: 0 20px;
  }
  

  .cart-header {
    display: flex;
    font-weight: 500;
    border: 1px solid #e8e8e8;
    height: 50px;
    line-height: 50px;
    background: #fafafa;
  
    .col-check {
      width: 100px;
      padding-left: 20px;
      display: flex;
      align-items: center;
      gap: 8px;
    }
    .col-name {
      width: 300px;
      margin-left: 150px;
    }
    .col-original {
      width: 180px;
      text-align: center;
    }
    .col-discount {
      width: 200px;
      text-align: center;
    }
    .col-operation {
      width: 80px;
      text-align: center;

      .delete-btn {
        border: 1px solid #f32425;
        background: transparent;
        color: #f32425;
        cursor: pointer;
        padding: 4px 8px;
        border-radius: 4px;
  
        &:hover {
          background: #f32425;
          color: #fff;
        }
      }
    }
  }
  
  .cart-list {
    .cart-item {
      display: flex;
      align-items: center;
      border: 1px solid #e8e8e8;
      margin: 20px 0;
      padding: 10px 0;
      height: 124px;
  
      .col-check {
        width: 50px;
        padding-left: 20px;
      }
      .col-name {
        width: 500px;
        .main-title {
          color: #333;
          font-size: 14px;
          margin-bottom: 4px;
        }
        .sub-title {
          color: #666;
          font-size: 12px;
          line-height: 1.4;
        }
      }
      .col-original {
        width: 180px;
        text-align: center;
        color: #999;
        .line-through {
          text-decoration: line-through;
        }
      }
      .col-discount {
        width: 200px;
        text-align: center;
        .discount-price {
          color: #f32425;
          font-weight: 600;
        }
        .tag {
          display: inline-block;
          margin-left: 8px;
          padding: 2px 5px;
          background: linear-gradient(48deg, #fe26b8, #f7283f);
          color: #fff;
          font-size: 12px;
          border-radius: 3px;
        }
      }
      .col-operation {
        width: 80px;
        text-align: center;
        display: flex;
        flex-direction: column;
        gap: 5px;
  
        button {
          border: none;
          background: transparent;
          cursor: pointer;
          color: #999;
  
          &:disabled {
            color: #ddd;
            cursor: not-allowed;
          }
          &:hover:not(:disabled) {
            color: #f32425;
          }
        }
      }
    }
  }
  
  .cart-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #eee;
    border: 1px solid #e4e4e4;
    border-right: 0;
    height: 60px;
    margin: 20px 0;
  
    .select-all {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-left: 18px;
    }
    .total {
      margin-left: 810px;
      .total-price {
        color: #f32425;
        font-size: 18px;
        font-weight: 600;
      }
    }
    .submit {
      width: 120px;
      height: 60px;
      background: #999;
      color: #fff;
      border: none;
      cursor: pointer;
      font-size: 20px;
      text-align: center;
      line-height: 60px;
  
      &:hover {
        background: #00b87c;
      }
    }
  }
  
  input[type="checkbox"] {
    width: 16px;
    height: 16px;
    cursor: pointer;
  }
  </style>